package com.gaoda.booksystem.web.sys;

import com.gaoda.booksystem.entity.Book;
import com.gaoda.booksystem.entity.User;
import com.gaoda.booksystem.sysService.SysUserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class UserManage {

    //分页
    private static final long serialVersionUID = 1L;
    private static final int PAGE_COUNT = 3;//每页显示记录数


    @Autowired
    SysUserService sysUserService;

    //模糊查询显示用户列表 + 分页
    @RequestMapping("/userList")
    public String queryUserList(String name, String userSex, String userDep, String userState, Model model, HttpServletRequest request) {
        //默认当前页
        int currentPage = 1;
        String page = request.getParameter("page");
        if (page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<User> list = sysUserService.queryUsers(name, userSex, userDep, userState, currentPage, PAGE_COUNT);
        int totalPage = sysUserService.getTotalPage(PAGE_COUNT, name, userSex, userDep, userState);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("list", list);
        model.addAttribute("name", name);
        model.addAttribute("userSex", userSex);
        model.addAttribute("userDep", userDep);

        return "sys/userManage";
    }

    //逻辑删除用户
    @RequestMapping("/deleteUser")
    @ResponseBody   //声明返回的数据为json格式
    public String deleteUser(int id) {
        try {
            System.out.println("delete" + id);
            sysUserService.deleteUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    //修改封停用户信息
    @RequestMapping("/updateUser")
    public String updateUser(Model model, int id) {
        User user = sysUserService.findUserById(id);
        sysUserService.updateUser(user);
        model.addAttribute("user", user);
        return "redirect:/userList";
    }

    //修改未封停用户信息
    @RequestMapping("/modifyUser")
    public String modifyUser(Model model, int id) {
        User user = sysUserService.findUserById(id);
        sysUserService.modifyUser(user);
        model.addAttribute("user", user);
        return "redirect:/userList";
    }

    //携带数据并跳转到修改用户信息的页面
    @RequestMapping("/jumpToModifyUser")
    public String jumpToModifyAdmin(Model model, User user, int id) {
//        System.out.println(id);
        if (id != 0) {
            user = sysUserService.findUserById(id);
//            System.out.println(user);
            model.addAttribute("user", user);
        }
        return "sys/userDetail";
    }

    //修改用户信息
    @RequestMapping("/updateUserManage")
    public String updateUserManage(User user, HttpServletRequest request) {
        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        int userSex = Integer.parseInt(request.getParameter("userSex"));
//        Date userTime = request.getParameter("userTime");

        String userTel = request.getParameter("userTel");
        String userDep = request.getParameter("userDep");
        int age = Integer.parseInt(request.getParameter("age"));
        user = new User(id, name, userSex, age, userDep, username, userTel);

        System.out.println(user);

        sysUserService.updateUserById(user);

        return "redirect:/userList";
    }

    //导出用户信息
    @RequestMapping(value = "/loadSysUser", method = RequestMethod.GET)
    public void loadBook(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("用户信息表");
        //获取数据
        List<User> userList = sysUserService.userList();

        //设置要导出的文件的名字
        String fileName = "UserList" + ".xls";

        //新增数据行，并且设置单元格数据
        int rowNum = 1;

        //headers表示excel表中第一行的表头
        String[] headers = {"用户名", "用户编号", "性别", "年龄", "注册时间", "电话号码", "所属部门", "用户类型"};

        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (User user : userList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(user.getName());
            row1.createCell(1).setCellValue(user.getUsername());
            String sex = (user.getUserSex()) == 1 ? "男" : "女";
            row1.createCell(2).setCellValue(sex);
            row1.createCell(3).setCellValue(user.getAge());
            row1.createCell(4).setCellValue(sdf.format(user.getUserTime()));
            row1.createCell(5).setCellValue(user.getUserTel());
            String u =user.getUserDep();
            String userDep = u.equals("1") ? "总经理办公室" :
                    ((u.equals("2") ? "人力资源部" :
                            (u.equals("3") ? "财务部" :
                                    ((u.equals("4") ? "生产技术部" :
                                            ((u.equals("5") ? "计划营销部" : (
                                                    (u.equals("6") ? "安全监察部" : "后勤部")))))))));
            row1.createCell(6).setCellValue(userDep);
            row1.createCell(7).setCellValue(user.getUserType());
            rowNum++;
        }

        //根据内容自动调整列宽
        HSSFSheet hssfSheet = workbook.getSheetAt(0);
        hssfSheet.autoSizeColumn((short) 0);
        hssfSheet.autoSizeColumn((short) 1);
        hssfSheet.autoSizeColumn((short) 2);
        hssfSheet.autoSizeColumn((short) 3);
        hssfSheet.autoSizeColumn((short) 4);
        hssfSheet.autoSizeColumn((short) 6);
        hssfSheet.autoSizeColumn((short) 7);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
